#include "NosepieceNikon.h"
#include <QDebug>

NosepieceNikon::NosepieceNikon(QObject *parent) : QObject(parent)
{
    m_lens = 0;
    m_nikon = new QAxObject(parent);
    m_nikon->setControl("Nikon.LvMic.NikonLV");

    qDebug() << "objectName = " << m_nikon->property("objectName");
    qDebug() << "SystemName = " << m_nikon->property("SystemName");
    qDebug() << "VersionOfSDK = " << m_nikon->property("VersionOfSDK");

    m_nosepiece = m_nikon->querySubObject("Nosepiece");
    m_timer = new QTimer(this);
    m_timer->setInterval(100);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(on_timer()));
    m_timer->start();
}

void NosepieceNikon::on_timer()
{
    int lens = m_nosepiece->property("_Position").toInt();
    if (lens != m_lens)
    {
        int oldLens = m_lens;
        m_lens = lens;
        if(m_lens != 0)
        {
            // Nikon 是从 1 开始计数的，而我们的代码是 0 开始计数，所以要 -1
            emit lensChanged(oldLens - 1, m_lens - 1);
        }
    }
}

bool NosepieceNikon::isMounted()
{
    return m_nosepiece->property("_IsMounted").toInt();
}

NosepieceNikon::~NosepieceNikon()
{
    delete m_nikon;
    m_timer->stop();
}

void NosepieceNikon::setLens(int lens)
{
    lens++; // Nikon 的物镜转盘是从 1 开始计数的。所以这里要 + 1
    int lowerLimit = m_nosepiece->property("_LowerLimit").toInt();
    int upperLimit = m_nosepiece->property("_UpperLimit").toInt();
    lens = qBound(lowerLimit, lens, upperLimit);
    m_nosepiece->setProperty("_Position", lens);
}

void NosepieceNikon::setLens(int oldLens, int newLens)
{
    qDebug() << "NosepieceNikon::setLens(int oldLens, int newLens)";
    qDebug() << "old = " << oldLens << ", new = " << newLens;
    Q_UNUSED(oldLens);// Nikon 控制器不需要 oldLens 信息
    newLens++; // Nikon 的物镜转盘是从 1 开始计数的。所以这里要 + 1
    int lowerLimit = m_nosepiece->property("_LowerLimit").toInt();
    int upperLimit = m_nosepiece->property("_UpperLimit").toInt();
    qDebug() << "lowerLimit = " << lowerLimit << ", upperLimit = " << upperLimit;
    newLens = qBound(lowerLimit, newLens, upperLimit);
    m_nosepiece->setProperty("_Position", newLens);
}

void NosepieceNikon::forward()
{
    m_nosepiece->dynamicCall("Forward()");
}

void NosepieceNikon::reverse()
{
    m_nosepiece->dynamicCall("Reverse()");
}
